package com.zxl.diy.weather.model.observable;

import com.zxl.diy.weather.model.PheadHelper;
import com.zxl.diy.weather.model.bean.City;
import com.zxl.diy.weather.model.bean.Weather;
import com.zxl.manager.privacy.utils.ApplicationHelper;
import com.zxl.manager.privacy.utils.model.Observable;
import com.zxl.manager.privacy.utils.utils.HttpUtils;
import com.zxl.manager.privacy.utils.utils.LogUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/11/6.
 */

public class QueryWeatherInfoObservable extends Observable<Weather, Integer, List<Weather>> {

    private City[] mCitys;

    private boolean mIs12Hour;

    public QueryWeatherInfoObservable(boolean mIs12Hour, City... mCitys) {
        this.mCitys = mCitys;
        this.mIs12Hour = mIs12Hour;
    }

    @Override
    public void run() {
        Map<String, String> header = PheadHelper.creatPheadHelp(ApplicationHelper.getContext());
        StringBuffer stringBuffer = new StringBuffer();
        StringBuffer timestamps = new StringBuffer();
        for (int i = 0; i < mCitys.length; i++) {
            if (i > 0) {
                stringBuffer.append(",");
                timestamps.append(",");
            }
            stringBuffer.append(mCitys[i].id);
            timestamps.append(mCitys[i].updateTimestamp);
        }
        header.put("w", stringBuffer.toString());
        header.put("h", mIs12Hour ? "12" : "24");
        header.put("timestamp", timestamps.toString());
        byte[] bytes = HttpUtils.doGet(PheadHelper.BASE_SERVICE_URL + "weather/getWeather", header);
        if (null != bytes && bytes.length > 0) {
            try {
                JSONObject jsonObject = new JSONObject(new String(bytes, "utf-8"));
                if (PheadHelper.isSuccessFromService(jsonObject)) {
                    LogUtils.d("jsonObject : " + jsonObject.toString());
                    return;
                } else {
                    handleFail(0);
                }
            } catch (Exception e) {
                e.printStackTrace();
                handleFail(-1);
            }
            handleComplete(null);
        }
    }
}
